import Vue from 'vue'
import VueRouter from 'vue-router'

import Detail from '@/views/article-detail.vue'
import Login from '@/views/login.vue'
import Register from '@/views/register.vue'
import Layout from '@/views/layout.vue'
//
import Collect from '@/views/collect.vue'
import Article from '@/views/article.vue'
import Like from '@/views/like.vue'
import User from '@/views/user.vue'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/detail/:id', component: Detail },
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    {
      path: '/',
      // redirect: '/article',
      redirect: '/login',
      component: Layout,
      children: [
        { path: '/collect', component: Collect },
        { path: '/article', component: Article },
        { path: '/like', component: Like },
        { path: '/user', component: User }
      ]
    }

  ]
})
// 全局前置导航守卫
// to  要去哪
// from 从哪来
// next() 放行函数  等价于  this.$router.push()
// next()   放行   next('/login')//强制到login页面
router.beforeEach((to, from, next) => {
// 1、获取token
  const token = getToken()
  // 2、有token想去哪就去哪
  if (token) {
    next()// 直接放行
  } else {
    // 3、如果没有登录，只能访问登录、注册页
    if (to.path === '/login' || to.path === '/register') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
